package com.ocm.core.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class XMLUtil {
   public static Document createDocument(InputStream inputStream) throws ParserConfigurationException, SAXException,
         IOException {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(inputStream);
      return doc;
   }

   public static Document newDocument(String root) throws ParserConfigurationException {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.newDocument();
      Element rootNode = doc.createElement(root);
      doc.appendChild(rootNode);
      return doc;
   }

   public static String convert(Document doc) {
      StringBuilder stringBuilder = null;
      try {
         ByteArrayOutputStream stream = new ByteArrayOutputStream();
         OutputFormat outputformat = new OutputFormat();
         outputformat.setIndent(4);
         outputformat.setIndenting(true);
         outputformat.setPreserveSpace(false);
         XMLSerializer serializer = new XMLSerializer();
         serializer.setOutputFormat(outputformat);
         serializer.setOutputByteStream(stream);
         serializer.asDOMSerializer();
         serializer.serialize(doc.getDocumentElement());
         stringBuilder = new StringBuilder(stream.toString());
      } catch (Exception except) {
         except.getMessage();
      }
      return stringBuilder.toString();
   }
}
